package com.thingsgrid.notice.config;

import com.alibaba.fastjson.JSON;
import com.thingsgrid.notice.entity.NoticeEntiy;
import com.thingsgrid.notice.service.InsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * MQTT接收信息
 * @author MQ
 */
@Component("messageHandler")
@Slf4j
public class MqttHandler implements MessageHandler {
    /**
     * 处理上线用户的未订阅消息
     */
    @Autowired
    private IMqttSender iMqttSender;
    @Autowired
    private InsService insService;
    @Override
    public void handleMessage(Message<?> message) {
        String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
        log.info("收到订阅消息: {}", topic);
        Object payLoad = message.getPayload();
        byte[] data = (byte[]) payLoad;
        String userTopic = new String(data);
        log.info("收到订阅消息1: {}", userTopic);
        List<NoticeEntiy> listn = insService.findByNames("receiver_name",userTopic);
        iMqttSender.sendToMqtt(userTopic,JSON.toJSONString(listn));
        log.info(listn.size()+"");

    }
}
